/**
 * 
 */
package ch.baeni.jee.data;

import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import ch.baeni.jee.model.User;

/**
 * @author Benjamin
 *
 */
@ApplicationScoped
public class UserRepository {
	
	@Inject
	private EntityManager em;
	
	public User findUserById(Long id){
		return em.find(User.class, id);
	}
	
	public User findUserByUsername(String username){
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<User> criteria = cb.createQuery(User.class);
		Root<User> user = criteria.from(User.class);
		criteria.select(user).where(cb.equal(user.get("username"), username));
		return em.createQuery(criteria).getSingleResult();
	}

	/**
	 * @return
	 */
	public List<User> findAllOrderedByName() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<User> criteria = cb.createQuery(User.class);
		Root<User> user = criteria.from(User.class);
		criteria.select(user);
		return em.createQuery(criteria).getResultList();
	}
}
